package com.demo.service.impl;

import com.demo.common.Arith;
import com.demo.common.Constants;
import com.demo.dao.ISaleCommissionDao;
import com.demo.dao.ISalePersonAccountDao;
import com.demo.dao.ISalePersonDao;
import com.demo.dao.UserWxMapper;
import com.demo.entity.*;
import com.demo.service.IOrderService;
import com.demo.service.ISaleCommissionService;
import com.demo.vo.SaleCommissionVo;
import com.demo.wx.AdvancedUtil;
import com.demo.wx.Template;
import com.demo.wx.TemplateParam;
import com.demo.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SaleCommissionImpl implements ISaleCommissionService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ISaleCommissionDao userDao;
    @Autowired
    private ISalePersonAccountDao spaDao;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ISalePersonDao salePersonDao;
    @Autowired
    private UserWxMapper userWxDao;

    @Override
    public List<SaleCommission> queryByPage(SaleCommissionVo user) {
        return userDao.queryByPage(user);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userDao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(SaleCommission record) {
        return userDao.insert(record);
    }

    @Override
    public int insertSelective(SaleCommission record) {
        return userDao.insertSelective(record);
    }

    @Override
    public SaleCommission selectByPrimaryKey(Integer id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(SaleCommission record) {
        return userDao.updateByPrimaryKeySelective(record);
    }

    /**
     * 佣金发放
     *
     * @param record record.orderId 必填，record.saleId
     * @return
     */
    @Override
    public Object giveCommission(SaleCommission record) {
        //佣金返现
        SaleCommission sc_res = userDao.selectOneByOrderId(record);
        if (sc_res != null) {
            int res_commsiion = sendComission(sc_res);
            Order order = orderService.selectByPrimaryKey(Integer.valueOf(sc_res.getOrderId()));

            if (res_commsiion > 0) {
                // todo：入账模板消息通知
                List<TemplateParam> paras = new ArrayList<TemplateParam>();
                paras.add(new TemplateParam("first", "您获得订单佣金提成" + sc_res.getCommission() + "元!", "#333333"));
                paras.add(new TemplateParam("order", order.getNo(), "#333333"));
                paras.add(new TemplateParam("money", String.valueOf(sc_res.getCommission()), "#333333"));
                paras.add(new TemplateParam("remark", "点击查看佣金账户及明细!", "#333333"));
                this.sendReturnedCommission(sc_res, paras);
                //模板消息通知
                record.setSaler(record.getSaleId());
                record.setSaleId(null);
                SaleCommission scManager = userDao.selectOneByOrderId(record);
                if (scManager != null) { //是某一销售经理销售员
                    int res_manager_commsiion = sendComission(scManager);
                    if (res_manager_commsiion > 0) {
                        // todo：入账模板消息通知
                        List<TemplateParam> paras_ = new ArrayList<TemplateParam>();
                        paras_.add(new TemplateParam("first", "您获得订单佣金提成" + sc_res.getCommission() + "元!", "#333333"));
                        paras_.add(new TemplateParam("order", order.getNo(), "#333333"));
                        paras_.add(new TemplateParam("money", String.valueOf(sc_res.getCommission()), "#333333"));
                        paras_.add(new TemplateParam("remark", "点击查看佣金账户及明细!", "#333333"));
                        this.sendReturnedCommission(scManager, paras_);
                    }
                }
            }

        }
        return null;

    }

    public int sendComission(SaleCommission sc_res) {
        sc_res.setStatus("1"); //1入账
        SalePersonAccount spa = new SalePersonAccount();
        Order order = orderService.selectByPrimaryKey(Integer.valueOf(sc_res.getOrderId()));
        SalePersonAccount spa_res = spaDao.selectBySaleID(sc_res.getSaleId());
        spa_res.setCashWillReceiveTotal(Arith.sub(spa_res.getCashWillReceiveTotal(), sc_res.getCommission()));
        sc_res.setCommission(Arith.mul(sc_res.getPercent(), order.getActualNumber()));
        spa_res.setCashCanWithDrawTotal(Arith.add(spa_res.getCashCanWithDrawTotal(), sc_res.getCommission()));
        spa_res.setCashTotal(Arith.add(spa_res.getCashTotal(), sc_res.getCommission())); //累计
        spaDao.updateByPrimaryKeySelective(spa_res);
        int res_commsiion = userDao.updateByPrimaryKeySelective(sc_res);
        return res_commsiion;
    }

    /**
     * @param sc     sc.saleId,sc.orderId
     * @param params 模板内容
     * @return
     */
    public Object sendReturnedCommission(SaleCommission sc, List<TemplateParam> params) {
        SalePerson salepManager = salePersonDao.selectByPrimaryKey(Integer.valueOf(sc.getSaleId()));
        if (salepManager.getOpenid() != null) {
            UserWx uwManager = new UserWx();
            uwManager.setUnionid(salepManager.getOpenid());
            uwManager.setUnitid(Constants.WXUserTypeWX);
            UserWx ux1Manager = userWxDao.selectByUnionid(uwManager);
            if (ux1Manager != null && ux1Manager.getOpenid() != null) { //系统包含微信账户
                Template tem = new Template();
                tem.setTemplateId(Constants.tmplReturnedCommission);
                tem.setTopColor("#00DD00");
                tem.setToUser(ux1Manager.getOpenid());
                tem.setUrl(Constants.domain + "/wx/user/index.html");
//                List<TemplateParam> paras = new ArrayList<TemplateParam>();
//                paras.add(new TemplateParam("first", "您将获得销售员" + sp.getName() + "订单销售经理提成" + scManger.getCommission() + "元!", "#333333"));
//                paras.add(new TemplateParam("order", order.getNo(), "#333333"));
//                paras.add(new TemplateParam("money", String.valueOf(scManger.getCommission()), "#333333"));
//                paras.add(new TemplateParam("remark", "点击查看佣金账户及明细!", "#333333"));
                tem.setTemplateParamList(params);
                AdvancedUtil.senderTmplSms(tem);
            }
        }
        return null;
    }

    @Override
    public int queryCount(SaleCommissionVo user) {
        return userDao.queryCount(user);
    }
}
